import { Tween } from 'cc';
import { _decorator, Component, Node, Label, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('UIDialog')
export class UIDialog extends Component {
    @property(Node)
    public content: Node;

    @property(Label)
    public label: Label;

    @property(Label)
    public confirmLabel: Label;

    @property(Label)
    public cancelLabel: Label;

    @property(Label)
    public bigConfirmLabel: Label;

    @property(Node)
    public confirm: Node;

    @property(Node)
    public cancel: Node;

    @property(Node)
    public bigConfirm: Node;

    // 动画
    private _tweenShow: Tween<Node>;
    private _tweenHide: Tween<Node>;
    private _tweenTime: number = .3;

    // 隐藏
    public onHide: (node: Node) => void = null;

    protected onLoad(): void {
        this.content.scale = Vec3.ZERO;
        this._tweenShow = this.content.DOScaleTo(this._tweenTime, Vec3.ONE, {
            easing: "cubicInOut"
        });

        this._tweenHide = this.content.DOScaleTo(this._tweenTime, Vec3.ZERO, {
            easing: "cubicInOut"
        }).call(() => {
            this.onHide && this.onHide(this.node);
        });
    }

    protected onEnable(): void {
        this.node.setSiblingIndex(this.node.parent.children.length);

        // 出现动画
        this._tweenShow.start();
    }

    public show(text: string, onConfirm?: () => void, onCancel?: () => void, yesBtnTxt?: string, noBtnTxt?: string): void {
        this.label.string = text;

        const hasCancel: boolean = onCancel != null || noBtnTxt != null;
        this.confirm.active = this.cancel.active = hasCancel;
        this.bigConfirm.active = !hasCancel;

        this.confirmLabel.string = this.bigConfirmLabel.string = yesBtnTxt ?? '确定';
        this.cancelLabel.string = noBtnTxt ?? '取消';

        const confirmCallback = () => {
            onConfirm && onConfirm();
            this.hide();
        };
        this.confirm.OnceClick(confirmCallback);
        this.bigConfirm.OnceClick(confirmCallback);

        this.cancel.OnceClick(() => {
            onCancel && onCancel();
            this.hide();
        });
    }

    public hide() {
        this._tweenHide.start();
    }
}